package com.hbue.springboot.controller;

import com.hbue.springboot.pojo.DTO.TbAccountDTO;
import com.hbue.springboot.pojo.Result;
import com.hbue.springboot.pojo.TbAccount;
import com.hbue.springboot.service.TbAccountService;
import com.hbue.springboot.utils.JWTUtils;
import com.hbue.springboot.utils.ResultCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能：
 * 日期：2025/1/12 16:20
 */
@Slf4j
@RestController
@RequestMapping("/account")
@RequiredArgsConstructor
public class TbAccountController {

    private final TbAccountService tbAccountService;

    /**
     * 处理前端的登录请求
     * @param account
     * @return Result
     */
    @PostMapping("/login")
    public Result login(@RequestBody TbAccount account) {
        log.info("login account:{}", account);
        TbAccountDTO res = tbAccountService.login(account.getUserName(), account.getUserPwd());
        if (res != null) {
            Map<String, String> map = new ConcurrentHashMap<>();
            map.put("id", String.valueOf(res.getId()));
            map.put("userName", res.getUserName());
            String token = JWTUtils.getToken(map);
            log.info("token:{}", token);
            res.setToken(token);
            return Result.success(res);
        } else {
            return Result.error(ResultCode.PASSWORD_ERROR);
        }
    }

    /**
     * 处理前端发起的修改密码请求
     * @param accountDTO 前端采集的数据
     * @return Result
     */
    @PostMapping("/modifyPassword")
    public Result modifyPassword(@RequestBody TbAccountDTO accountDTO) {
        log.info(" modify pwd account = "+accountDTO);
        // 根据用户名修改密码
        int rs = tbAccountService.modifyUserPwd(accountDTO);
        // 条件成立： 修改密码成功
        if (rs == 1) {

            return Result.success(rs);
        } else if (rs == 0) {
            return Result.error("修改密码失败");
        }else {
            return Result.error("原密码错误");
        }
    }
    @GetMapping("/{id}")
    public Result modifyPassword(@PathVariable("id") Long id) {
        TbAccountDTO rs =   tbAccountService.getUserById(id);
        return Result.success(rs);
    }

    /**
     * 修改个人信息
     * @param id
     * @param accountDTO
     * @return
     */
    @PutMapping("/{id}")
    public Result updateUserInfo(@PathVariable("id") Integer id, @RequestBody TbAccountDTO accountDTO) {
        int updated = tbAccountService.updateUserInfo(id, accountDTO);
        if (updated>0) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }
}
